<?php
session_start();

require("include/config.inc.php");
require("include/mysql.inc.php");

$azione = @$_GET["action"];
$user = @$_POST["username"];
$pass = @$_POST["password"];
$rem = @$_POST["rem"];

$log_days = 15;

if($azione != "logout")
{
	$db = new MySQL();
	
	$db->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_DEBUG);
	
	$db->query("SELECT  username, tipo  FROM Utente WHERE username = '$user' AND password = PASSWORD('$pass')");
	//$db->query("SELECT username, tipo FROM Utente WHERE username = '" . $user . "' AND password = '" . $pass . "'");
	
	if($db->get_num_rows() > 0)
	{
		$row = $db->fetch_array();
		
		if($rem == "on")
		{
			setcookie("login[user]", $row["username"] , time() + 60 * 60 * 24 * $log_days);
			setcookie("login[type]", $row["tipo"], time() + 60 * 60 * 24 * $log_days);
		}
		
		$_SESSION["user"] = $row["username"];
		$_SESSION["type"] = $row["tipo"];
		
		if($row["tipo"] == "admin")
		{
			header("Location: admin_opt.php");
			exit;
		}
		else
		{
			header("Location: user_opt.php");
			exit;
		}
	}
	else
	{
		session_unset();
		session_destroy();
		
		header("Location: login.php?error=si");
		exit;
	}
	
	$db->free_result();
	$db->close();
}
else
{
	if(isset($_COOKIE["login"]))
	{
		setcookie("login[user]", "", time() - 60 * 60 * 24 * $log_days);
		setcookie("login[type]", "", time() - 60 * 60 * 24 * $log_days);
	}
	
	session_unset();
	session_destroy();
	
	header("Location: login.php");
	exit;
}
?>
